/**
 * 
 */
var _playerNamed;
var _gamesDisplayed = [];
$(document).ready(function()
	{
	$.fancybox({
		'href':'logIn.html',
		'type':'iframe',
		'width':500,
		'height':250,
		'autoSize':false,
		'fitToView':false,
		'closeClick':false,
		'closeBtn':false,
		helpers :{
		 overlay : {
			 closeClick : false,
			 css : {
				 'cursor': 'red'
			 }}
		},
	    'afterClose': function(){
	    	_playerNamed = $("a#name").attr("href");
	    	nameQuery();
	    }
		});
	$(".fancybox-close").unbind(); 
	$(".fancybox-close").hide(); 
	
	$('#hostGameBtn').click(function()
			{
			$.ajax({type: "POST",url:"./game", data:{Name:String(_playerNamed),Status:2},dataType:"text",success: function(responseJson)
						{
						var json = JSON.parse(responseJson);
						$.fancybox({href:"./manguLeht.html?id="+json.gameId, 
							type:'iframe',
							autoSize:false,
							fitToView:false,
							width:'100%',
							height:'100%'
							});
					
						}});
				

			});
	$("#replayBtn").click(function()
			{
				$("#replayBtn").fancybox({
					'type':'iframe',
					'width':250,
					'height':300,
					'autoSize':false
					});
			});
	function nameQuery(){
		$.ajax({url: "./lobby",method:"GET",success:function(responseJson)
			{
			 	var playerNames = responseJson.players;
			 	$("#namesTable").children().remove();
			 	for (i=0;i<playerNames.length;i++)
			 	{
			 		$("#namesTable").append("<tr class='tableRowPassive'><td class='nameTableCell'>"+String(playerNames[i])+"<td><tr>");
			 	}
			},dataType:"json"});
		}
			
	setInterval(nameQuery,5000);
	
	setInterval(function (){
		$.ajax({url: "./game", method: "GET",
		success: function(responseJson){
			$('#gamesTable').children().remove();
			$.each(responseJson,function(index,item){
				if (item[0]=="2")
				{
					$('#gamesTable').append("<tr class='tableRowActive' id='tr"+String(index)+"'><td class='gameTableCell' id='td"+String(index)+"'> Mang: "+String(index)+" looja: "+String(item[1])+"<td><tr>");
				}
				else
				{
					$('#gamesTable').append("<tr class='tableRowPassive' id='tr"+String(index)+"'><td class='gameTableCellPassive' id='td"+String(index)+"'> Mang: "+String(index)+" looja: "+String(item[1])+"<td><tr>");
				}	
			});
		}, dataType:"json"});
	},3000);
$(window).on('beforeunload', function (){
	$.post("./lobby",{Name:String(_playerNamed),Status:0});
});	
});
$(window).load(function(){
	$("#gamesTable").on('click','.tableRowActive',function()
			{
				if (_playerNamed!=0)
				{
					$.post("./game",{Name:String(_playerNamed),GameID:(parseInt($(this).attr('id').split("tr")[1])),Status:3});
					$.fancybox({href:"./manguLeht.html?id="+($(this).attr('id').split("tr")[1]), 
					type:'iframe',
					autoSize:false,
					fitToView:false,
					width:'100%',
					height:'100%'
					});
				}
			});	
	
});